package com.party.web.biz.member;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.party.common.constant.Constant;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.commune.CUserIntegral;
import com.party.core.model.member.PackageCount;
import com.party.core.model.notify.Event;
import com.party.core.model.notify.InstanceWay;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.model.notify.TargetTemplateType;
import com.party.core.model.system.TargetType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.ITargetTemplateService;
import com.party.core.service.member.IPackageCountService;
import com.party.core.service.notify.IEventService;
import com.party.notify.notifyPush.integral.INotifyMemberIntegralSendService;
import com.party.notify.notifyPush.integral.MemberIntegralSendFactory;
import com.party.web.biz.quartz.impl.ScheduleJobService;
import com.party.web.biz.quartz.impl.SchsduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 批量添加积分后，发送消息业务处理
 *
 * @Date: 2019/10/16 10:20
 */
@Service
public class MemberIntegralNotifyService {

    @Autowired
    private IActivityService activityService;
    @Autowired
    private IEventService eventService;
    @Autowired
    private ITargetTemplateService targetTemplateService;

    @Autowired
    private MemberIntegralSendFactory memberIntegralSendFactory;

    @Autowired
    private IPackageCountService packageCountService;

    @Autowired
    private ScheduleJobService scheduleJobService;

    /***
     * 批量添加积分后发送短信
     * @Date 9:18 2019/10/16
     * @param cUserIntegral
     * @param actPublisher
     * @return
     **/
    public void sendAddIntegraSms(CUserIntegral cUserIntegral, String actPublisher, String behavior, TargetTemplate targetTemplate, Date date, Integer type) throws Exception {

        // 定时的时间小于当前时间, 则直接立即执行
        if (date.getTime() < System.currentTimeMillis()) {
            if ("add".equals(behavior)) {
                this.sendAndSave(cUserIntegral, targetTemplate, actPublisher);
            } else if ("modifyTime".equals(behavior)) {
                throw new BusinessException("时间参数有误, 该时间将永远不会执行 dateTime = " + date);
            } else {
                this.send(targetTemplate.getId());
            }
            return;
        }

        targetTemplate.setSendTime(date);
        String tempId = null;
        boolean hasTemp;
        if ("add".equals(behavior)) {
            targetTemplate.setId(null);
            if (Constant.SEND_SHORT_MESSAGE_TYPE_INTEGRAL.equals(type)) {
                tempId = this.save(cUserIntegral,targetTemplate);
            }
            hasTemp = false;
        } else {
            // 如果是修改发送时间, 需要检测该短信是否已经发送了
            if ("modifyTime".equals(behavior)) {
                TargetTemplate dbTemp = targetTemplateService.get(targetTemplate.getId());
                Date sendTime = dbTemp.getSendTime();
                if (null != sendTime && sendTime.getTime() < System.currentTimeMillis()) {
                    throw new BusinessException("该短信已经发送了, 请刷新页面");
                }
            }
            targetTemplateService.update(targetTemplate);
            tempId = targetTemplate.getId();
            hasTemp = true;
        }

        if (StringUtils.isEmpty(tempId)) {
            throw new BusinessException("保存定时发送短信模板失败, template = " + targetTemplate);
        }

        String cron = DateUtils.formatDate(date, "s m HH d M ? yyyy");

        final String clazz = "quartzBizSendShortMessage";
        final String method = "send";

        List<Object> params = Lists.newArrayList();
        params.add(type);

        Event event;
        if (hasTemp) {
            event = eventService.findByCode(clazz);
            event.setCronExpression(cron);
            scheduleJobService.dynamicUpdate(event, tempId, SchsduleService.GROUP_SEND_SHORT_MESSAGE, params);
        } else {
            event = new Event();
            event.setWay(com.party.common.constant.Constant.EVENT_AUTO);
            event.setName(SchsduleService.JOB_SEND_SHORT_MESSAGE);
            event.setCode(clazz);
            event.setType("4");
            event.setCronExpression(cron);
            event.setIsSync(0);
            event.setClassName(clazz);
            event.setMethod(method);
            scheduleJobService.dynamicInsert(event, tempId, SchsduleService.GROUP_SEND_SHORT_MESSAGE, params);
        }
    }


    /**
     * 发送消息and保存模板
     *
     * @param targetTemplate 目标模板
     */
    public boolean sendAndSave(CUserIntegral cUserIntegral, TargetTemplate targetTemplate, String actPublisher) {
        if (Strings.isNullOrEmpty(targetTemplate.getTemplate())) {
            throw new BusinessException("模板内容不能为空");
        }
        //保存
        targetTemplate.setId(null);
        targetTemplate.setInitiatorId(actPublisher);
        Date now = new Date();
        targetTemplate.setCreateDate(now);
        targetTemplate.setUpdateDate(now);
        targetTemplate.setSendTime(now);
        targetTemplate.setCiItemId(cUserIntegral.getIntegralItemId());
        targetTemplate.setCiTypeId(cUserIntegral.getIntegralTypeId());
        targetTemplate.setMemberType(cUserIntegral.getMemberType());
        targetTemplateService.insert(targetTemplate);

        return this.memberIntegralRealSend(targetTemplate, actPublisher);
    }


    /**
     * 会员积分短信真实发送
     *
     * @param targetTemplate 模板
     * @param orgId          机构id
     */
    public boolean memberIntegralRealSend(TargetTemplate targetTemplate, String orgId) {
        PackageCount packageCount = packageCountService.getUnique(new PackageCount(orgId, TargetType.PUSH_SMS.getCode()));
        if (packageCount != null && YesNoStatus.YES.getCode().equals(packageCount.getIsOpen())) {
            Integer spareNum = packageCountService.getSpareNum(packageCount.getTotalNum(), packageCount.getUseNum());
            targetTemplate.setSpareNum(spareNum);
        }

        TargetTemplateType targetTemplateType = TargetTemplateType.get(targetTemplate.getType());
        INotifyMemberIntegralSendService sender = memberIntegralSendFactory.getSender(targetTemplateType);

        return sender.send(targetTemplate, targetTemplate.getTargetId(), orgId, InstanceWay.ORGANIZATION.getName());
    }


    /**
     * 发送消息and保存模板
     *
     * @param id 目标模板id
     */
    public boolean send(String id) {
        TargetTemplate targetTemplate = targetTemplateService.get(id);
        if (Strings.isNullOrEmpty(targetTemplate.getTemplate())) {
            throw new BusinessException("模板内容不能为空");
        }
        Activity activity = activityService.get(targetTemplate.getTargetId());
        if (null == activity) {
            throw new BusinessException("找不到活动");
        }

        return this.memberIntegralRealSend(targetTemplate, activity.getMember());
    }

    public String save(CUserIntegral cUserIntegral,TargetTemplate targetTemplate) {
        if (Strings.isNullOrEmpty(targetTemplate.getTemplate())){
            throw new BusinessException("模板内容不能为空");
        }
        Activity activity = activityService.get(targetTemplate.getTargetId());
        if (null == activity){
            throw new BusinessException("找不到众筹项目");
        }
        //保存
        targetTemplate.setInitiatorId(activity.getMember());
        targetTemplate.setCiItemId(cUserIntegral.getIntegralItemId());
        targetTemplate.setCiTypeId(cUserIntegral.getIntegralTypeId());
        targetTemplate.setMemberType(cUserIntegral.getMemberType());
        return targetTemplateService.insert(targetTemplate);
    }

}
